package vip.xiaonuo.smzq.modular.kcl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.locationtech.jts.geom.Point;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.core.enums.AuditphaseEnum;
import vip.xiaonuo.smzq.core.enums.ErrorEnum;
import vip.xiaonuo.smzq.core.enums.ResultEnum;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.core.utils.TransFormUtil;
import vip.xiaonuo.smzq.core.utils.UserUtil;
import vip.xiaonuo.smzq.modular.deom.MdbTool;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb08Xzqh;
import vip.xiaonuo.smzq.modular.dictionary.entity.vo.DirTree;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.hisi.entity.vo.CxtjMhtj;
import vip.xiaonuo.smzq.modular.kcl.entity.*;
import vip.xiaonuo.smzq.modular.kcl.entity.param.XzqhCxtj;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.*;
import vip.xiaonuo.smzq.modular.kcl.mapper.ClspczrzMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.KsMapper;
import vip.xiaonuo.smzq.modular.kcl.service.*;
import vip.xiaonuo.smzq.modular.lifecycle.util.CoordinateTranUtil;
import vip.xiaonuo.smzq.modular.psba.entity.vo.PsbaGtJbqkVo;
import vip.xiaonuo.smzq.modular.psba.entity.vo.PsbaXqVo;
import vip.xiaonuo.smzq.modular.user.entity.Org;
import vip.xiaonuo.smzq.modular.user.entity.Role;
import vip.xiaonuo.smzq.modular.user.entity.User;
import vip.xiaonuo.smzq.modular.user.mapper.OrgMapper;
import vip.xiaonuo.smzq.modular.user.mapper.PositionMapper;
import vip.xiaonuo.smzq.modular.user.mapper.RoleMapper;
import vip.xiaonuo.smzq.modular.user.mapper.UserMapper;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.KsAutocompleteVo;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 矿山基本信息 服务实现类
 *
 * @author eomer
 * @since 2024-02-22
 */
@Service
public class KsServiceImpl extends ServiceImpl<KsMapper, Ks> implements IKsService {

    @Resource
    CoordinateTranUtil coordinateTranUtil;
    @Resource
    private KsMapper ksMapper;

    @Resource
    private IKsshjlService iKsshjlService;

    @Resource
    private IZyclService iZyclService;//资源储量

    @Resource
    private IZbService iZbService;//坐标

    @Resource
    private IKsjjService iKsjjService;//矿山经济

    @Resource
    private IKcpService iKcpService;//矿产品

    @Resource
    private ICxhService iCxhService;//采选环

    @Resource
    private IZhhsService iZhhsService;//综合回收

    @Resource
    private IDztjService iDztjService;//地质条件

    @Resource
    private IBgService iBgService;//报告

    @Resource
    private IYfService iYfService;//压覆

    @Resource
    private IBazyclService iBazyclService;//备案资源储量

    @Resource
    private IZlscService iZlscService;//文件上传

    @Resource
    private IWjglbService iWjglbService;//资料关联
    @Resource
    private ICkqsqdjService iCkqsqdjService;//采矿权登记
    @Resource
    private ITkqsqdjService iTkqsqdjService;//探矿权登记

    @Resource
    private RoleMapper roleMapper;//角色


    @Resource
    private IClspService iClspService;//储量填报审批
    @Resource
    private OrgMapper orgMapper;//级别部省市县填报
    @Resource
    private PositionMapper positionMapper;//所对应的行政区划
    @Resource
    private UserMapper userMapper;//用户
    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;//行政区划

    @Resource
    private ClspczrzMapper clspczrzMapper;//操作日志

    @Resource
    private ISjyjService iSjyjService;//数据预警

    @Value("${file.base}")
    String baseFilePath;

    @Override
    public Page<Ks> page(Ks ks) {
        QueryWrapper<Ks> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }


    @Override
    public Page<KsCxtj> getKspage(CxtjMhtj cxtjMhtj) {
        Page<KsCxtj> page = new Page<>();


        return page;
    }

    /**
     * 拼接sql
     */
    public String getSql(CxtjMhtj cxtjMhtj) {
        String sql = "";
        //拼接年度信息
        if (cxtjMhtj.getNd() != null) {
            sql += " and nd = " + cxtjMhtj.getNd();
        }
        //拼接矿山名称信息
        if (cxtjMhtj.getKsmc() != null) {
            sql += " and ksmc like '%" + cxtjMhtj.getKsmc() + "%'";
        }
        //拼接矿山编号信息
        if (cxtjMhtj.getKsmc() != null) {
            sql += " and ksmc like '%" + cxtjMhtj.getKsmc() + "%'";
        }
        //拼接矿区编号信息
        if (cxtjMhtj.getKqbh() != null) {
            sql += " and kqbh = like '%" + cxtjMhtj.getKqbh() + "%'";
        }
        //拼接矿区名称
        if (cxtjMhtj.getKqmc() != null) {
            sql += " and kqmc = like '%" + cxtjMhtj.getKqmc() + "%'";
        }
        //拼接矿种
        if (cxtjMhtj.getKzbh() != null) {
            sql += " and kzbh = " + cxtjMhtj.getKzbh();
        }
        //登记分类编号
        if (cxtjMhtj.getDjflbh() != null) {
            sql += " and djflbh = " + cxtjMhtj.getDjflbh();
        }
        //矿业权人
        if (cxtjMhtj.getKyqr() != null) {
            sql += " and kyqr = '" + cxtjMhtj.getKyqr() + "'";
        }
        //有效期模糊查询
        if (cxtjMhtj.getYxq() != null) {
            sql += " and yxq = like '%" + cxtjMhtj.getYxq() + "%'";
        }
        //行政区代码级联多选
        if (cxtjMhtj.getXzqh() != null) {
            List<Integer> xzqhList = Arrays.stream(cxtjMhtj.getXzqh().split(","))
                    .map(String::trim) // 去除前后空白
                    .map(Integer::parseInt) // 转换为Integer
                    .collect(Collectors.toList());
            String insql = "(";
            for (Integer xzqh : xzqhList) {
                insql += xzqh + ",";
            }
            insql = insql.substring(0, insql.length() - 1) + ")";
            sql += " and xzqh in " + insql;
        }
        //行政区代码
        if (cxtjMhtj.getXzqdm() != null) {
            String xzqh = String.valueOf(cxtjMhtj.getXzqdm());
            xzqh = xzqh.replaceAll("0+$", "");
            if (xzqh.length() == 6) {//若输入的是县
                sql += " and xzqdm = " + cxtjMhtj.getXzqdm();
            }
            if (xzqh.length() == 4) {//若输入的是市
                String insql = "(";
                List<Integer> xianList = cb08XzqhMapper.selectXzqhDm(cxtjMhtj.getXzqdm());
                for (Integer xian : xianList) {
                    insql += xian + ",";
                }
                insql = insql.substring(0, insql.length() - 1) + ")";
                sql += " and xzqdm in " + insql;

            }
            if (xzqh.length() == 2) {//若输入的是省
                List<Integer> shiList = cb08XzqhMapper.selectXzqhDm(cxtjMhtj.getXzqdm());
                QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("fdm", shiList);
                List<Cb08Xzqh> cb08Xzqhs = cb08XzqhMapper.selectList(queryWrapper);
                String insql = "(";
                for (Cb08Xzqh cb08Xzqh : cb08Xzqhs) {
                    insql += cb08Xzqh.getDm() + ",";
                }
                insql = insql.substring(0, insql.length() - 1) + ")";
                sql += " and xzqdm in " + insql;
            }

        }
        //许可证号
        if (cxtjMhtj.getXkzh() != null) {
            sql += " and xkzh = '" + cxtjMhtj.getXkzh() + "'";
        }

        sql = sql.substring(4, sql.length());

        return " where " + sql;
    }


    /**
     * 矿山基本信息目录树
     * param xzqhDm 行政区划代码
     * param nd 年度0
     */
    @Override
    public List<DirTree> ksDirTreelist(Integer xzqhDm, Integer nd) {

        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());
        // Position position = positionMapper.selectById(user.getPositionId());

        Role role = roleMapper.selectById(user.getPositionId());
        String xkzh = user.getXkzh(); //用户许可证号
        List<DirTree> dirTreeList = new ArrayList<>();
        List<String> kqbhs = new ArrayList<>();

        String xzqh = "";

        if (xzqhDm != null) {
            xzqh = String.valueOf(xzqhDm);
        } else {
            xzqh = user.getOrgId();
        }


        xzqh = xzqh.replaceAll("0+$", "");
        boolean ifkqr = false;  //是否是矿业权人
        try {
            //填报人员
            if (role.getCode().equals("zt7qwacif0")) {
                kqbhs = ksMapper.getKqbhKqr(xzqh, nd, xkzh);
                ifkqr = true;
            } else {//非填报人员
                kqbhs = ksMapper.getKqbh(xzqh, nd);
            }
            if (kqbhs != null && kqbhs.size() > 0) {
                for (String kqbh : kqbhs) {
                    DirTree dirTree = new DirTree();
                    dirTree.setId(kqbh);
                    dirTree.setPId("0");
                    dirTree.setName(kqbh);
                    //dirTree.setLeaf(false);
                    dirTree.setChildren(ksDirTrees(kqbh, nd, ifkqr, xkzh));
                    dirTreeList.add(dirTree);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return dirTreeList;
    }


    /**
     * 矿山基本信息目录树
     * param xzqhCxtj 参数
     */
    @Override
    public List<DirTree> ksDirTreelistNew(XzqhCxtj xzqhCxtj) {
        //当前用户的行政区划代码
        String xzqhdm = UserUtil.getCurrentUserXzqhdm().replaceAll("0+$", "");
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        // Position position = positionMapper.selectById(user.getPositionId());
        Role role = roleMapper.selectById(saBaseLoginUser.getPositionId());
        String xkzh = saBaseLoginUser.getXkzh(); //用户许可证号
        List<DirTree> dirTreeList = new ArrayList<>();
        List<Object> kqbhs = new ArrayList<>();

//        String sql = "";
//        //年度必传
//        if (xzqhCxtj.getNd() != null) {
//            sql += " and nd = " + xzqhCxtj.getNd();
//        } else {
//            return dirTreeList;
//        }
//        //行政区划
//        if (xzqhCxtj.getXzqdm() != null && xzqhCxtj.getXzqdm().length() > 0) {
//            sql += " and xzqdm:: VARCHAR like '" + xzqhCxtj.getXzqdm() + "%'";
//        }
//        //许可证号
//        if (xzqhCxtj.getXkzh() != null && xzqhCxtj.getXkzh().length() > 0) {
//            sql += " and xkzh like '%" + xzqhCxtj.getXkzh() + "%'";
//        }
//        //矿区编号
//        if (xzqhCxtj.getKqbh() != null && xzqhCxtj.getKqbh().length() > 0) {
//            sql += " and kqbh like '%" + xzqhCxtj.getKqbh() + "%'";
//        }
//        //矿山编号
//        if (xzqhCxtj.getKsbh() != null && xzqhCxtj.getKsbh().length() > 0) {
//            sql += " and ksbh like '%" + xzqhCxtj.getKsbh() + "%'";
//        }
//        //矿山名称
//        if (xzqhCxtj.getKsmc() != null && xzqhCxtj.getKsmc().length() > 0) {
//            sql += " and ksmc like '%" + xzqhCxtj.getKsmc() + "%'";
//        }
//        //矿业权人
//        if (xzqhCxtj.getKyqr() != null && xzqhCxtj.getKyqr().length() > 0) {
//            sql += " and kyqr like '%" + xzqhCxtj.getKyqr() + "%'";
//        }
//        //矿区名称
//        if (xzqhCxtj.getKqmc() != null && xzqhCxtj.getKqmc().length() > 0) {
//            sql += " and ksmc like '%" + xzqhCxtj.getKqmc() + "%'";
//        }
        boolean ifkqr = false;  //是否是矿业权人
        try {
//            //填报人员
//            if (role.getCode().equals("zt7qwacif0")) {
//                sql += " and xkzh = '" + xkzh + "'";
//                ifkqr = true;
//            }

            MPJLambdaWrapper<Ks> wrapper = new MPJLambdaWrapper<>();
            wrapper.select(Ks::getKqbh);

// 年度必传
            if (xzqhCxtj.getNd() == null) {
                return dirTreeList; // 如果年度为空，直接返回
            }
            wrapper.eq(ObjUtil.isNotEmpty(xzqhCxtj.getNd()), Ks::getNd, xzqhCxtj.getNd());

// 行政区划
            wrapper.likeRight(ObjUtil.isNotEmpty(xzqhCxtj.getXzqdm()), "t.xzqdm :: VARCHAR", xzqhCxtj.getXzqdm());
// 行政区划
            wrapper.likeRight(ObjUtil.isNotEmpty(xzqhdm), "t.xzqdm :: VARCHAR", xzqhdm);

// 许可证号
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getXkzh()), Ks::getXkzh, xzqhCxtj.getXkzh());

// 矿区编号
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getKqbh()), Ks::getKqbh, xzqhCxtj.getKqbh());

// 矿山编号
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getKsbh()), Ks::getKsbh, xzqhCxtj.getKsbh());

// 矿山名称
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getKsmc()), Ks::getKsmc, xzqhCxtj.getKsmc());

// 矿业权人
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getKyqr()), Ks::getKyqr, xzqhCxtj.getKyqr());

// 矿区名称
            wrapper.like(ObjUtil.isNotEmpty(xzqhCxtj.getKqmc()), Ks::getKsmc, xzqhCxtj.getKqmc());

            wrapper.ne(Ks::getSbbs,3);

            wrapper.ne(Ks::getKqbh,"");
            wrapper.groupBy(Ks::getKqbh);
            wrapper.orderByAsc(Ks::getKqbh);

            //填报人员
            if (role.getCode().equals("zt7qwacif0")) {
                wrapper.eq(ObjUtil.isNotEmpty(xzqhCxtj.getXkzh()), Ks::getXkzh, xkzh);
                ifkqr = true;
            }


//            kqbhs = ksMapper.getKqbhList(sql, xzqhdm);
            kqbhs = ksMapper.selectObjs(wrapper);
            if (kqbhs != null && kqbhs.size() > 0) {
                for (Object kqbhObj : kqbhs) {
                    String kqbh = String.valueOf(kqbhObj);
                    DirTree dirTree = new DirTree();
                    dirTree.setId(kqbh);
                    dirTree.setPId("0");
                    dirTree.setName(kqbh);
                    //dirTree.setLeaf(false);
                    dirTree.setChildren(ksDirTreesNew(kqbh, xzqhCxtj, ifkqr, xkzh));
                    dirTreeList.add(dirTree);
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return dirTreeList;
    }

    /**
     * 新建矿山基本信息
     *
     * @param ks
     */
    @Override
    public void insertKs(Ks ks, MultipartFile file) {
        boolean flag = checkKs(ks);
        if (flag) {
            //读取mdb数据
            if (file != null) {
                getMdaKsData(ks, file);
            }
            ksMapper.insert(ks);
        }
    }

    /**
     * 删除矿山基本信息
     *
     * @param ks
     */
    @Override
    public void deleteKs(Ks ks) {
        String sql = "";
        String clspSql = "";
        if (ks.getKqbh() != null && ks.getKqbh().length() > 0) {
            sql += "kqbh='" + ks.getKqbh() + "'";
            clspSql += "kqbh='" + ks.getKqbh() + "'";
        } else {
            throw new CommonException("矿区编号" + ErrorEnum.KCL_KS_ISNULL);

        }

        if (ks.getNd() != null && ks.getNd() > 0) {
            sql += " and nd=" + ks.getNd();
            clspSql += " and nd=" + ks.getNd();
        } else {
            throw new CommonException("年度" + ErrorEnum.KCL_KS_ISNULL);
        }

        if (ks.getDjflbh() != null && ks.getDjflbh() > 0) {
            sql += " and djflbh=" + ks.getDjflbh();
            clspSql += " and djflbm=" + ks.getDjflbh();
        }

        ksMapper.delectKs(sql, clspSql);


    }


    /**
     * 新建时校验矿区矿山
     *
     * @param ks
     * @return
     */
    public boolean checkKs(Ks ks) {
        boolean flag = false;
        //矿区编号不能为空
        if (ks.getKqbh() == null || ks.getKqbh().length() == 0) {
            throw new CommonException("矿区编号" + ErrorEnum.KCL_KS_ISNULL);
        } else if (ks.getDjflbh() == 1000) {
            LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Ks::getKqbh, ks.getKqbh());
            queryWrapper.eq(Ks::getDjflbh, 1000);
            List<Ks> ksList = ksMapper.selectList(queryWrapper);
            if (ksList.size() > 0) {
                throw new CommonException("该矿区" + ErrorEnum.KCL_KS_ISEXIST);
            }
        }

        //登记分类编号不能为空
        if (ks.getDjflbh() == null) {
            throw new CommonException("登记分类编号" + ErrorEnum.KCL_KS_ISNULL);
        } else {
            int firstPlace = ks.getDjflbh() / 1000;
            if (firstPlace != 1 && firstPlace != 2) {
                throw new CommonException("" + ErrorEnum.KCL_KS_DJFLBH);
            } else {
                LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Ks::getKqbh, ks.getKqbh());
                queryWrapper.eq(Ks::getDjflbh, ks.getDjflbh());
                List<Ks> ksList = ksMapper.selectList(queryWrapper);
                if (ksList.size() > 0) {
                    throw new CommonException("该登记分类编号" + ErrorEnum.KCL_KS_ISEXIST);
                }
            }


        }
        //矿区编号不能为空
        if ((ks.getXkzh() == null || ks.getXkzh().length() == 0) && ks.getDjflbh() != 1000) {
            throw new CommonException("许可证号" + ErrorEnum.KCL_KS_ISNULL);
        } else {
            LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Ks::getXkzh, ks.getXkzh());
            queryWrapper.eq(Ks::getNd, ks.getNd());
            List<Ks> ksList = ksMapper.selectList(queryWrapper);
            if (ksList.size() > 0) {
                throw new CommonException("该许可证号" + ErrorEnum.KCL_KS_ISEXIST);
            }
        }
        flag = true;

        return flag;
    }


    public List<DirTree> ksDirTrees(String kqbh, Integer nd, boolean ifkqr, String xkzh) {
        List<DirTree> dirTreeList = new ArrayList<>();
        QueryWrapper<Ks> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kqbh", kqbh);
        queryWrapper.eq("nd", nd);
        if (ifkqr) {
//            queryWrapper.ge("djflbh", 2000);
//            queryWrapper.le("djflbh", 3000);
            queryWrapper.eq("xkzh", xkzh);
        }
        queryWrapper.orderByAsc("djflbh");
        List<Ks> ksList = ksMapper.selectList(queryWrapper);
        for (Ks ks : ksList) {
            DirTree dirTree = new DirTree();
            dirTree.setId(ks.getPkid());
            dirTree.setPId(kqbh);
            dirTree.setName(String.valueOf(ks.getDjflbh()));
            dirTree.setCode(ks.getKsbh());
            //dirTree.setLeaf(true);
            dirTree.setCus(ks);
            dirTreeList.add(dirTree);
        }


        return dirTreeList;
    }

    public List<DirTree> ksDirTreesNew(String kqbh, XzqhCxtj xzqhCxtj, boolean ifkqr, String xkzh) {
        List<DirTree> dirTreeList = new ArrayList<>();
        QueryWrapper<Ks> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kqbh", kqbh);
        queryWrapper.eq("nd", xzqhCxtj.getNd());

        //行政区划
//        if (xzqhCxtj.getXzqdm() != null&&xzqhCxtj.getXzqdm().length()>0){
//            queryWrapper.like("xzqdm",Integer.valueOf(xzqhCxtj.getXzqdm()));
//        }
        //许可证号
        if (xzqhCxtj.getXkzh() != null && xzqhCxtj.getXkzh().length() > 0) {
            queryWrapper.like("xkzh", xzqhCxtj.getXkzh());

        }
//        //矿区编号
        if (xzqhCxtj.getKqbh() != null && xzqhCxtj.getKqbh().length() > 0) {
            queryWrapper.like("kqbh", xzqhCxtj.getKqbh());

        }
        //矿山编号
        if (xzqhCxtj.getKsbh() != null && xzqhCxtj.getKsbh().length() > 0) {
            queryWrapper.like("ksbh", xzqhCxtj.getKsbh());

        }
        //矿山名称
        if (xzqhCxtj.getKsmc() != null && xzqhCxtj.getKsmc().length() > 0) {
            queryWrapper.like("ksmc", xzqhCxtj.getKsmc());

        }
        //矿业权人
        if (xzqhCxtj.getKyqr() != null && xzqhCxtj.getKyqr().length() > 0) {
            queryWrapper.like("kyqr", xzqhCxtj.getKyqr());

        }
        //矿区名称
        if (xzqhCxtj.getKqmc() != null && xzqhCxtj.getKqmc().length() > 0) {
            queryWrapper.like("ksmc", xzqhCxtj.getKqmc());
        }

        if (ifkqr) {
//            queryWrapper.ge("djflbh", 2000);
//            queryWrapper.le("djflbh", 3000);
            queryWrapper.eq("xkzh", xkzh);
        }
        queryWrapper.orderByAsc("djflbh");
        List<Ks> ksList = ksMapper.selectList(queryWrapper);
        for (Ks ks : ksList) {
            DirTree dirTree = new DirTree();
            dirTree.setId(ks.getPkid());
            dirTree.setPId(kqbh);
            dirTree.setName(String.valueOf(ks.getDjflbh()));
            dirTree.setCode(ks.getKsbh());
            //dirTree.setLeaf(true);
            dirTree.setCus(ks);
            dirTreeList.add(dirTree);
        }


        return dirTreeList;
    }


    /**
     * 审核列表
     *
     * @param user 用户
     * @Author yxt
     */
    @Override
    public Page<Ks> auditList(SaBaseLoginUser user) {
        LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
        //判断人员性质
        //部门类别
        if (user.getOrgCategory().equals(AuditphaseEnum.K_J.getCode())) {
            //矿山
            queryWrapper.eq(Ks::getKyqr, user.getOrgName());
        } else {
            if (AuditphaseEnum.getByCode(user.getOrgCategory()).getSub() != 0) {
                String str = StringUtils.substring(user.getOrgCode(), 0, AuditphaseEnum.getByCode(user.getOrgCategory()).getSub());
                Integer integer = bqXzqh(str, 6, "0");
                Integer integer1 = bqXzqh(str, 6, "9");
                queryWrapper.between(Ks::getXzqdm, bqXzqh(str, 6, "0"), bqXzqh(str, 6, "9"));
            }
        }

        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public String audit(String ksId, Integer result, String opinions, SaBaseLoginUser user) {
        Ks ks = this.getById(ksId);

        if (result.equals(ResultEnum.Yes.getCode())) {
            ks.setAudit(AuditphaseEnum.getCodeByValue(AuditphaseEnum.getByCode(user.getOrgCategory()).getValue() + 1));
            if (AuditphaseEnum.getByCode(user.getOrgCategory()).getValue() + 1 == AuditphaseEnum.W_J.getValue()) {
                ks.setSbbs(1);
                ks.setShyj(opinions);
                ks.setAudit(AuditphaseEnum.W_J.getCode());
            }
        } else {
            ks.setShzt(result);
            ks.setShyj(opinions);
            ks.setAudit(AuditphaseEnum.getCodeByValue(AuditphaseEnum.getByCode(user.getOrgCategory()).getValue() - 1));
        }
        this.updateById(ks);
        addShjl(ks, user, result, opinions);
        return null;
    }

    @Override
    public String submitAudit(String ksId, SaBaseLoginUser user) {
        Ks ks = this.getById(ksId);
        ks.setSbbs(2);
        ks.setAudit(AuditphaseEnum.X_J.getCode());
        ks.setShzt(null);
        ks.setShyj(null);
        this.updateById(ks);
        addShjl(ks, user, null, null);
        return null;
    }

    /**
     * 添加审核记录
     *
     * @param ks       矿山基本信息
     * @param user     用户
     * @param result   审核结果
     * @param opinions 审核意见
     */
    public void addShjl(Ks ks, SaBaseLoginUser user, Integer result, String opinions) {
        //添加矿山审核记录kcl_ksshjl
        Ksshjl ksshjl = new Ksshjl();
        ksshjl.setKsid(ks.getPkid());
        ksshjl.setNd(ks.getNd());
        ksshjl.setDjflbh(ks.getDjflbh());
        ksshjl.setKqbh(ks.getKqbh());
        ksshjl.setKsbh(ks.getKsbh());
        ksshjl.setKsmc(ks.getKsmc());
        ksshjl.setKyqr(ks.getKyqr());
        ksshjl.setTbr(ks.getTbr());
        ksshjl.setAudit(user.getOrgCategory());
        ksshjl.setShzt(result);
        ksshjl.setShyj(opinions);
        ksshjl.setCjr(user.getName());
        ksshjl.setCjsj(new Timestamp(System.currentTimeMillis()));
        iKsshjlService.save(ksshjl);
    }

    public Integer bqXzqh(String str, Integer leng, String code) {
        if (str.length() < leng) {
            for (int i = str.length(); i < leng; i++) {
                str += code;
            }
        }
        return Integer.parseInt(str);
    }

    /**
     * 矿山基本信息及其关联
     */
    @Override
    public KsDetails getKsDetails(Integer nd, String kqbh, Integer djflbh) {
        KsDetails ksDetails = new KsDetails();
        try {
            Integer djflbm = 1000;
            if (djflbh != null) {
                djflbm = djflbh;
            }

            //查询矿石基本信息
            QueryWrapper<Ks> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("kqbh", kqbh);
            queryWrapper.eq("djflbh", djflbm);
            queryWrapper.eq("nd", nd);
            Ks ks = ksMapper.selectOne(queryWrapper);
            if (ks != null) {
                ksDetails.setKs(ks);
            } else {
                ksDetails.setKs(new Ks());
            }

            // 资源储量列表查询
            List<ResourceReserves> resourceReservesList = iZyclService.getResourceReservesList(ks.getKqbh(), djflbh, ks.getNd());
            if (resourceReservesList != null && resourceReservesList.size() > 0) {
                ksDetails.setResourceReserves(resourceReservesList);
            } else {
                ksDetails.setResourceReserves(new ArrayList<>());
            }

            //坐标
            Coordinates coordinates = iZbService.getCoordinates(kqbh, djflbm, nd);
            if (coordinates != null) {
                ksDetails.setCoordinates(coordinates);
            } else {
                ksDetails.setCoordinates(new Coordinates());
            }

            //矿山经济
            Ksjj ksjj = iKsjjService.getKsjjDetails(kqbh, djflbm, nd);
            if (ksjj != null) {
                ksDetails.setKsjj(ksjj);
            } else {
                ksDetails.setKsjj(new Ksjj());
            }

            //矿产品
            List<Kcp> kcpList = iKcpService.getKcpList(kqbh, djflbm, nd);
            if (kcpList != null && kcpList.size() > 0) {
                ksDetails.setKcpList(kcpList);
            } else {
                ksDetails.setKcpList(new ArrayList<>());
            }


            //采选环
            Cxh cxh = iCxhService.getCxh(kqbh, djflbm, nd);
            if (cxh != null) {
                ksDetails.setCxh(cxh);
            } else {
                ksDetails.setCxh(new Cxh());
            }

            //综合回收
            List<ZhhsDetails> zhhsList = iZhhsService.getZhhsList(kqbh, djflbm, nd);
            if (zhhsList != null && zhhsList.size() > 0) {
                ksDetails.setZhhsList(zhhsList);
            } else {
                ksDetails.setZhhsList(new ArrayList<>());
            }

            //地质条件
            Dztj dztj = iDztjService.getDztj(kqbh, djflbm, nd);
            if (dztj != null) {
                ksDetails.setDztj(dztj);
            } else {
                ksDetails.setDztj(new Dztj());
            }

            //报告
            List<Bg> bds = iBgService.getBgList(kqbh, djflbm, nd);
            if (bds != null && bds.size() > 0) {
                ksDetails.setBgList(bds);
            } else {
                ksDetails.setBgList(new ArrayList<>());
            }

            //压覆
            List<Yf> yfList = iYfService.getYfList(kqbh, djflbm, nd);
            if (yfList != null && yfList.size() > 0) {
                ksDetails.setYfList(yfList);
            } else {
                ksDetails.setYfList(new ArrayList<>());
            }

            //备案资源储量
            List<List<BazyclDetails>> bazyclList = iBazyclService.getBazyclList(kqbh, djflbm, nd);
            if (bazyclList != null && bazyclList.size() > 0) {
                ksDetails.setBazyclList(bazyclList);
            } else {
                ksDetails.setBazyclList(new ArrayList<>());
            }

            //资料上传文件关联表
            List<Zlxqcx> zlxqcxList = iWjglbService.getZlxqcxList(djflbm, kqbh, nd);
            if (zlxqcxList != null && zlxqcxList.size() > 0) {
                ksDetails.setZlxqcxList(zlxqcxList);
            } else {
                ksDetails.setZlxqcxList(new ArrayList<>());
            }
//
//            //采矿权申请登记详情
//            Ckqsqdj ckqsqdj = iCkqsqdjService.getCkqsqdj(nd, kqbh, djflbm);
//            if (ckqsqdj != null) {
//                ksDetails.setCkqsqdj(ckqsqdj);
//            }
//
//            //探矿权申请登记详情
//            Tkqsqdj tkqsqdj = iTkqsqdjService.getTkqsqdj(djflbm, kqbh, nd);
//            if (tkqsqdj != null) {
//                ksDetails.setTkqsqdj(tkqsqdj);
//            }


        } catch (Exception e) {
            System.out.println(e);
        }


        return ksDetails;
    }

    /**
     * 添加矿山基本信息及其关联
     */
    @Override
    public String addKsDetails(KsDetails ksDetails) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();

        String xkzh = ksDetails.getKs().getXkzh();
        int xzqdm = ksDetails.getKs().getXzqdm();
        Integer nd = ksDetails.getKs().getNd();
        String kqbh = ksDetails.getKs().getKqbh();
        Integer djflbm = ksDetails.getKs().getDjflbh();
        String kyqr = "";
        if (ksDetails.getKs() != null) {
            kyqr = ksDetails.getKs().getKyqr();
        }


        String result = "";
        try {
            result = saveKsDetails(ksDetails);
            //进行储量审核
            Clsp clsp = new Clsp();
            clsp.setKqbh(kqbh);
            clsp.setDjflbm(djflbm);
            clsp.setNd(nd);
            clsp.setXkzh(xkzh);
            if (ksDetails.getKs().getKsbh() != null) {
                clsp.setKsbh(ksDetails.getKs().getKsbh());
            }
            //县
            clsp.setXian(String.valueOf(xzqdm));
            //市
            QueryWrapper<Cb08Xzqh> shiWrapper = new QueryWrapper<>();
            shiWrapper.eq("dm", xzqdm);
            Cb08Xzqh shi = cb08XzqhMapper.selectOne(shiWrapper);
            clsp.setShi(String.valueOf(shi.getFdm()));
            //省
            QueryWrapper<Cb08Xzqh> shengWrapper = new QueryWrapper<>();
            shengWrapper.eq("dm", shi.getFdm());
            Cb08Xzqh sheng = cb08XzqhMapper.selectOne(shengWrapper);
            clsp.setSheng(String.valueOf(sheng.getFdm()));
            //矿权人
//            if (ksDetails.getKs().getKyqr() != null){
//                clsp.setKyqr(ksDetails.getKs().getKyqr());
//            }
            //创建人
            clsp.setCreatBy(saBaseLoginUser.getId());
            clsp.setKyqr(kyqr);
            //创建时间
            clsp.setCteatTime(DateUtil.format(new Date(), "YYYYMMdd"));
            clsp.setTbzt("已填报");
            clsp.setSpzt("1");
            //查询数据库，是否已经有审批记录若有则不在新增，否则新增
            QueryWrapper<Clsp> clspWrapper = new QueryWrapper<>();
            clspWrapper.eq("kqbh", kqbh);
            clspWrapper.eq("djflbm", djflbm);
            clspWrapper.eq("nd", nd);
            clspWrapper.eq("tbzt", "已填报");
            clspWrapper.last("limit 1");
            //组织数据进行操作日志的补充
            Clsp clspOld = iClspService.getOne(clspWrapper);
            Clspczrz clspczrz = new Clspczrz();

            String clspId = "";
            if (clspOld == null) {
                clsp.setGxsj(DateUtil.format(new Date(), "YYYYMMddHHmmss"));
                iClspService.save(clsp);
                clspId = clsp.getPkid();
            } else {
                clspOld.setGxsj(DateUtil.format(new Date(), "YYYYMMddHHmmss"));
                clspOld.setSpzt("1");
                clspId = clspOld.getPkid();
                iClspService.updateById(clspOld);
            }

            clspczrz.setCzlx("已填报");
            clspczrz.setCzrid(saBaseLoginUser.getId());
            clspczrz.setCzrxm(saBaseLoginUser.getName());
            clspczrz.setCzsj(DateUtil.format(new Date(), "YYYY-MM-dd HH-mm-ss"));
            clspczrz.setNbspid(clspId);

            clspczrzMapper.insert(clspczrz);

            //删除对应填报消息预警
            if (djflbm > 2000 && djflbm < 3000) {
                //删除填报消息预警
                iSjyjService.delectSjyj(nd, djflbm, kqbh, 308002);
            } else {
                iSjyjService.delectSjyj(nd, djflbm, kqbh, 308001);
            }


        } catch (Exception e) {
            System.out.println(e);
            result = "添加失败" + e;
        }

        return result;
    }

    @Override
    public HomeRelated getHomeRelated(Integer nd) {
        HomeRelated homeRelated = new HomeRelated();
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        BeanUtil.copyProperties(saBaseLoginUser, homeRelated);

        User user = userMapper.selectById(saBaseLoginUser.getId());
        Org org = orgMapper.selectById(user.getOrgId());

        Role role = roleMapper.selectById(user.getPositionId());
        String code = role.getCode();
        //   Position position = positionMapper.selectById(user.getPositionId());

        List<KsVo> ksList = new ArrayList<>();
        if (code != null) {
            if (code.equals("shengsh")) { //省账户
                int shengsh = Integer.valueOf(org.getId());
                homeRelated.setSheng(shengsh);
                List<Integer> shiList = cb08XzqhMapper.selectXzqhDm(shengsh);
                QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("fdm", shiList);
                List<Cb08Xzqh> cb08Xzqhs = cb08XzqhMapper.selectList(queryWrapper);
                for (Cb08Xzqh cb08Xzqh : cb08Xzqhs) {
                    ksList.addAll(getXzqhks(nd, cb08Xzqh.getDm()));
                }

            } else if (code.equals("shish")) { //市账户
                // int shish = Integer.parseInt(position.getCode());
                int shish = Integer.valueOf(org.getId());
                homeRelated.setShi(shish);

                QueryWrapper<Cb08Xzqh> queryWrapperSheng = new QueryWrapper<>();
                queryWrapperSheng.eq("dm", shish);
                Cb08Xzqh cb08Xian1 = cb08XzqhMapper.selectOne(queryWrapperSheng);
                homeRelated.setSheng(cb08Xian1.getFdm());
                QueryWrapper<Cb08Xzqh> queryWrapperShi = new QueryWrapper<>();
                queryWrapperShi.eq("fdm", shish);
                List<Cb08Xzqh> cb08Xian = cb08XzqhMapper.selectList(queryWrapperShi);
                for (Cb08Xzqh cb08 : cb08Xian) {
                    ksList.addAll(getXzqhks(nd, cb08.getDm()));
                }


            } else if (code.equals("xiansh")) {//县
                int xian = Integer.valueOf(org.getId());
                homeRelated.setXian(xian);

                QueryWrapper<Cb08Xzqh> queryWrapperShi = new QueryWrapper<>();
                queryWrapperShi.eq("dm", xian);
                Cb08Xzqh shi = cb08XzqhMapper.selectOne(queryWrapperShi);
                homeRelated.setShi(shi.getFdm());

                QueryWrapper<Cb08Xzqh> queryWrapperSheng = new QueryWrapper<>();
                queryWrapperSheng.eq("dm", shi.getFdm());
                Cb08Xzqh sheng = cb08XzqhMapper.selectOne(queryWrapperSheng);
                homeRelated.setSheng(sheng.getFdm());

                ksList.addAll(getXzqhks(nd, xian));
            } else if (code.equals("superAdmin") || code.equals("bjsh")) { //系统，部级
                int shengsh = 130000;
                homeRelated.setSheng(shengsh);
                List<Integer> shiList = cb08XzqhMapper.selectXzqhDm(shengsh);
                QueryWrapper<Cb08Xzqh> queryWrapper = new QueryWrapper<>();
                queryWrapper.in("fdm", shiList);
                List<Cb08Xzqh> cb08Xzqhs = cb08XzqhMapper.selectList(queryWrapper);
                for (Cb08Xzqh cb08Xzqh : cb08Xzqhs) {
                    ksList.addAll(getXzqhks(nd, cb08Xzqh.getDm()));
                }
            }
        }

        homeRelated.setKsList(ksList);

        return homeRelated;
    }

    @Override
    public List<Ks> selectList(QueryWrapper<Ks> queryWrapperKs) {
        return ksMapper.selectList(queryWrapperKs);
    }


    public List<KsVo> getXzqhks(Integer nd, Integer dm) {

        QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
        queryWrapperKs.eq("xzqdm", dm);
        queryWrapperKs.eq("nd", nd);
        List<Ks> ksList = ksMapper.selectList(queryWrapperKs);
        List<KsVo> returnList = new ArrayList<>();
        for (Ks ks : ksList) {
            if (ks.getZxdxzb() != null && ks.getZxdyzb() != null) {
                DecimalFormat df = new DecimalFormat("#.##########");
                Point point = ConvertCoordinates4490(df.format(ks.getZxdxzb()), df.format(ks.getZxdyzb()));
                if (point != null) {
                    ks.setZxdxzb(point.getX());
                    ks.setZxdyzb(point.getY());
                }
                KsVo ksVo = new KsVo();
                BeanUtil.copyProperties(ks, ksVo);
                int djflbhm = 0;

                if (ks.getDjflbh() != null) {
                    djflbhm = ks.getDjflbh() / 1000;
                    if (djflbhm == 2) {
                        ksVo.setKyqlx("2");
                    } else {
                        if ((ks.getKyqr() != null && !ks.getKyqr().equals("")) || (ks.getXkzh() != null && !ks.getXkzh().equals(""))) {
                            ksVo.setKyqlx("1");
                        } else {
                            ksVo.setKyqlx("0");
                        }
                    }
                }
                returnList.add(ksVo);
            }

        }

        return returnList;

    }

    public Point ConvertCoordinates4490(String x, String y) {
        Point point = null;
        int dotIndex = x.indexOf('.');
        if (dotIndex == 2) {
            String substitution = y;
            y = x;
            x = substitution;

            //将度分秒转成经纬度
            x = String.valueOf(coordinateTranUtil.dmsToWgs84(Double.parseDouble(x)));
            y = String.valueOf(coordinateTranUtil.dmsToWgs84(Double.parseDouble(y)));
        }
        x = x.replace(",", "");
        y = y.replace(",", "");


        /**
         * 检查输入的度分秒点坐标
         *
         * @param x 经度
         * @param y 纬度
         */
        if (TransFormUtil.pointDFM(x, y) != null) {
            return TransFormUtil.pointDFM(x, y);
        }
        /**
         * 检查输入的十进制度点坐标
         *
         * @param x 经度
         * @param y 纬度
         */
        if (TransFormUtil.pointDecimalism(x, y) != null) {
            return TransFormUtil.pointDecimalism(x, y);

        }
        /**
         * 检查输入的2000大地点坐标
         *
         * @param x 经度
         * @param y 纬度
         */
        if (TransFormUtil.pointEPSG4490(x, y) != null) {
            return TransFormUtil.pointEPSG4490(x, y);
        }


        return point;
    }

    /**
     * 数据同步，下一年的年报任务生成
     * 年度 nd
     * 矿区编号 kqbh
     * 登记分类编号 djflbh
     */

    public Boolean generateAnnualReportTask(Integer nd, String kqbh, Integer djflbh) {
        try {
            KsDetails ksDetails = getKsDetails(nd, kqbh, djflbh);
            //资源储量数据同步
            boolean zyclData = iZyclService.synchronizationZyclData(kqbh, djflbh, nd);

            nd = nd + 1;
            //矿山基本信息数据同步
            Ks ks = ksDetails.getKs();
            if (ks != null) {
//                   String uuid= UUID.randomUUID().toString();
                ks.setNd(nd);
                ks.setPkid(null);
                //避免重复数据先执行删除
                QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
                queryWrapperKs.eq("kqbh", kqbh).eq("djflbh", djflbh).eq("nd", nd);
                ksMapper.delete(queryWrapperKs);

                ksMapper.insert(ks);
            }

            //报告
            if (ksDetails.getBgList() != null) {
                List<Bg> bgList = ksDetails.getBgList();
                List<Bg> bgListNew = new ArrayList<>();
                for (Bg bg : bgList) {
                    bg.setNd(nd);
                    bg.setPkid(null);
                    bgListNew.add(bg);
                }
                //避免重复数据先执行删除
                iBgService.delete(kqbh, djflbh, nd);
                iBgService.addList(bgListNew, kqbh, djflbh, nd);
            }
            //添加坐标
            if (ksDetails.getCoordinates() != null) {
                Coordinates coordinates = ksDetails.getCoordinates();
                coordinates.setNd(nd);
                coordinates.setPkid(null);
                //避免重复数据先执行删除
                iZbService.delect(kqbh, djflbh, nd);
                iZbService.addZb(coordinates);
            }

            //矿山经济
            if (ksDetails.getKsjj() != null) {
                int jjCount = iKsjjService.addKsjj(ksDetails.getKsjj(), kqbh, djflbh, nd);
                System.out.println("矿山经济已同步" + jjCount + "条");
            }
            //矿产品
            if (ksDetails.getKcpList() != null) {
                int kcpCount = iKcpService.addList(ksDetails.getKcpList(), kqbh, djflbh, nd);
                System.out.println("矿产品已同步" + kcpCount + "条");
            }

            //采选环
            if (ksDetails.getCxh() != null) {
                int cxhCount = iCxhService.addCxh(ksDetails.getCxh(), kqbh, djflbh, nd);
                System.out.println("采选环已同步" + cxhCount + "条");

            }

            //综合回收
            if (ksDetails.getZhhsList() != null) {
                int zhhsCount = iZhhsService.addList(ksDetails.getZhhsList(), kqbh, djflbh, nd);
                System.out.println("综合回收已同步" + zhhsCount + "条");
            }


            //地质条件
            if (ksDetails.getDztj() != null) {
                int dztjCount = iDztjService.addDztj(ksDetails.getDztj(), kqbh, djflbh, nd);
                System.out.println("地质条件已同步" + dztjCount + "条");
            }

            //备案资源量
            if (ksDetails.getBazyclList() != null) {
                int bazyclCount = iBazyclService.addList(ksDetails.getBazyclList(), kqbh, djflbh, nd);
                System.out.println("备案资源量已同步" + bazyclCount + "条");
            }

            //压覆
            if (ksDetails.getYfList() != null) {
                int yfCount = iYfService.addList(ksDetails.getYfList(), kqbh, djflbh, nd);
                System.out.println("压覆已同步" + yfCount + "条");
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据许可证号获取矿山基本信息及其关联
     *
     * @Param 许可证号 xkzh
     * return PsbaXqVo
     */
    @Override
    public PsbaXqVo getKs(String xkzh) {
        PsbaXqVo psbaXqVo = new PsbaXqVo();
        //根据许可证号查询最新矿山数据
        QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
        queryWrapperKs.eq("xkzh", xkzh);
        queryWrapperKs.between("djflbh", 2000, 3000);
        queryWrapperKs.orderByDesc("nd");
        queryWrapperKs.last("limit 1");
        Ks ks = ksMapper.selectOne(queryWrapperKs);
        if (ks != null) {
            //KsDetails ksDetails = getKsDetails(ks.getNd(), ks.getKqbh(), ks.getDjflbh());
            //根据矿山基本情况回显评审备案基本情况
            PsbaGtJbqkVo PsbaGtJbqkVo = new PsbaGtJbqkVo();
            BeanUtil.copyProperties(ks, PsbaGtJbqkVo);
            QueryWrapper<Cb08Xzqh> xianWrapper = new QueryWrapper<>();
            xianWrapper.eq("dm", ks.getXzqdm());
            Cb08Xzqh xian = cb08XzqhMapper.selectOne(xianWrapper);
            PsbaGtJbqkVo.setXzqhMc(xian.getMc());
            PsbaGtJbqkVo.setKqmc(ks.getKsmc());
            PsbaGtJbqkVo.setSsksbh(Integer.valueOf(ks.getKsbh()));
            PsbaGtJbqkVo.setDjflbh(ks.getDjflbh());
            psbaXqVo.setPsbaGtJbqk(PsbaGtJbqkVo);

//
//            //评审备案报告
//            if (ksDetails.getBgList() != null&&ksDetails.getBgList().size()>0){
//                Bg bg = ksDetails.getBgList().get(0);
//                PsbaGtBg psbaGtBg=new PsbaGtBg();
//                BeanUtil.copyProperties(bg, psbaGtBg);
//                psbaXqVo.setPsbaGtBg(psbaGtBg);
//            }


            return psbaXqVo;
        }
        return new PsbaXqVo();
    }

    @Override
    public String saveKsDetails(KsDetails ksDetails) {
        Integer nd = ksDetails.getKs().getNd();
        String kqbh = ksDetails.getKs().getKqbh();
        Integer djflbm = ksDetails.getKs().getDjflbh();
        String result = "";
        try {
            if (ksDetails.getKs() != null) {
                //添加矿山基本信息
                int i = ksMapper.updateById(ksDetails.getKs());
                if (i > 0) {
                    result = "矿山基本信息成功添加:" + i + "条;";
                } //else {
//                    result = result + "矿山基本信息添加失败;";
//                }
            }

            //添加资源储量
            // Integer count = iZyclService.addList(ksDetails.getZyclList());
//            if (count > 0) {
//                result = result + "资源储量成功添加:" + count + "条;";
//            }else{
//                result=result+"资源储量成功添加失败;";
//            }
            Coordinates coordinates = ksDetails.getCoordinates();
            //添加坐标
            if (coordinates != null) {
                coordinates.setNd(nd);
                coordinates.setKqbh(kqbh);
                coordinates.setDjflbh(djflbm);

                int zbCount = iZbService.addZb(coordinates);
                if (zbCount > 0) {
                    result = result + "坐标信息成功添加:" + zbCount + "条;";
                }
//                else {
//                    result = result + "坐标信息成功添加失败;";
//                }
            }

            //添加矿山经济
            if (ksDetails.getKsjj() != null) {
                int jjCount = iKsjjService.addKsjj(ksDetails.getKsjj(), kqbh, djflbm, nd);
                if (jjCount > 0) {
                    result = result + "矿山经济信息成功添加:" + jjCount + "条;";
                }
//                else {
//                    result = jjCount + "矿山经济信息成功添加失败;";
//                }
            }


            //添加矿产品
            if (ksDetails.getKcpList() != null) {
                int kcpCount = iKcpService.addList(ksDetails.getKcpList(), kqbh, djflbm, nd);
                if (kcpCount > 0) {
                    result = result + "矿产品信息成功添加:" + kcpCount + "条;";
                }
//                else {
//                    result = kcpCount + "矿产品信息成功添加失败;";
//                }
            }


            //采选环
            if (ksDetails.getCxh() != null) {
                int cxhCount = iCxhService.addCxh(ksDetails.getCxh(), kqbh, djflbm, nd);
                if (cxhCount > 0) {
                    result = result + "采选环信息成功添加:" + cxhCount + "条;";
                }
//                else {
//                    result = cxhCount + "采选环信息成功添加失败;";
//                }
            }


            //综合回收
            if (ksDetails.getZhhsList() != null) {
                int zhhsCount = iZhhsService.addList(ksDetails.getZhhsList(), kqbh, djflbm, nd);
                if (zhhsCount > 0) {
                    result = result + "综合回收信息成功添加:" + zhhsCount + "条;";
                }
//                else {
//                    result = zhhsCount + "综合回收信息成功添加失败;";
//                }
            }


//地质条件
            if (ksDetails.getDztj() != null) {
                int dztjCount = iDztjService.addDztj(ksDetails.getDztj(), kqbh, djflbm, nd);
                if (dztjCount > 0) {
                    result = result + "地质条件信息成功添加:" + dztjCount + "条;";
                }
//                else {
//                    result = dztjCount + "地质条件信息成功添加失败;";
//                }
            }

//            //报告
            if (ksDetails.getBgList() != null) {
                int bgCount = iBgService.addList(ksDetails.getBgList(), kqbh, djflbm, nd);
                if (bgCount > 0) {
                    result = result + "报告信息成功添加:" + bgCount + "条;";
                }
//                else {
//                    result = bgCount + "报告信息成功添加失败;";
//                }
            }

//            //压覆
            if (ksDetails.getYfList() != null) {
                int yfCount = iYfService.addList(ksDetails.getYfList(), kqbh, djflbm, nd);
                if (yfCount > 0) {
                    result = result + "压覆信息成功添加:" + yfCount + "条;";
                }
//                else {
//                    result = yfCount + "压覆信息成功添加失败;";
//                }
            }


            //备案资源储量
            if (ksDetails.getBazyclList() != null) {
                int bazyclCount = iBazyclService.addList(ksDetails.getBazyclList(), kqbh, djflbm, nd);
                if (bazyclCount > 0) {
                    result = result + "资源储量信息成功添加:" + bazyclCount + "条;";
                }
            }
        } catch (Exception e) {

            result = "添加失败";
            e.printStackTrace();
        }
        return result;
    }


    /**
     * @param ksmc 矿山名称
     * @param nd   年度
     * @return java.util.List<vip.xiaonuo.smzq.modular.kcl.entity.Ks>
     * @description 获取自动填充矿山信息
     * @author bigStrong
     * @date 2024/7/18 19:28
     */
    @Override
    public List<KsAutocompleteVo> autocompleteKsList(String ksmc, Integer nd, String flag) {
        Page<Ks> ksPage = new Page<Ks>(1, 20);
        List<KsAutocompleteVo> list = new ArrayList<KsAutocompleteVo>();

        LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(nd != null, Ks::getNd, nd)
                .like(ksmc != null && !ksmc.isEmpty(), Ks::getKsmc, ksmc);
        if (flag != null && !flag.isEmpty()) {
            switch (flag) {
                case "1":
                    queryWrapper.eq(Ks::getDjflbh, 1000);
                    break;
                case "2":
                    queryWrapper.between(Ks::getDjflbh, 2000, 3000);
                    break;
                case "3":
                    queryWrapper.between(Ks::getDjflbh, 3000, 4000);
                    break;
                case "4":
                    queryWrapper.ge(Ks::getDjflbh, 4000);
                    break;
                default:
                    break;
            }
        } else {
            queryWrapper.le(Ks::getDjflbh, 4000);
        }
        queryWrapper.in(Ks::getSbbs, 1, 2);
        Page<KsAutocompleteVo> ksAutocompleteVoPage = ksMapper.getKsAutocompleteList(ksPage, queryWrapper);

        if (ksAutocompleteVoPage != null) {
            list = ksAutocompleteVoPage.getRecords();
        }
        return list;
    }


    /**
     * 储量查询-过滤行政区划目录树
     *
     * @Param xzqhCxtj
     */
    @Override
    public List<String> filterXzqh(XzqhCxtj xzqhCxtj) {
        //当前用户的行政区划代码
        String xzqhdm = UserUtil.getCurrentUserXzqhdmNoInterception();
        List<String> xzqhList = new ArrayList<>();
        xzqhList.add("130000");
        List<String> xzqhListsel = new ArrayList<>();

        String fistXzq = xzqhdm.replaceAll("0+$", "");
        try {
            if (xzqhCxtj.getNd() != null) {
                //按行政区划做条件搜索
                if (xzqhCxtj.getXzqdm() != null && xzqhCxtj.getXzqdm().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhdm(fistXzq, xzqhCxtj.getXzqdm());
                }

                //按矿区编号做条件搜索
                if (xzqhCxtj.getKqbh() != null && xzqhCxtj.getKqbh().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhKqbh(fistXzq, xzqhCxtj.getKqbh(), xzqhCxtj.getNd());

                }
                //按矿山编号做条件搜索
                if (xzqhCxtj.getKsbh() != null && xzqhCxtj.getKsbh().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhKsbh(fistXzq, xzqhCxtj.getKsbh(), xzqhCxtj.getNd());

                }

                //按矿山名称做条件搜索
                if (xzqhCxtj.getKsmc() != null && xzqhCxtj.getKsmc().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhKqmc(fistXzq, xzqhCxtj.getKsmc(), xzqhCxtj.getNd());

                }

                //按矿区名称做条件搜索
                if (xzqhCxtj.getKqmc() != null && xzqhCxtj.getKqmc().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhKqmc(fistXzq, xzqhCxtj.getKqmc(), xzqhCxtj.getNd());
                }

                //按矿业权人做条件搜索
                if (xzqhCxtj.getKyqr() != null && xzqhCxtj.getKyqr().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhKyqr(fistXzq, xzqhCxtj.getKyqr(), xzqhCxtj.getNd());
                }

                //按许可证号做条件搜索
                if (xzqhCxtj.getXkzh() != null && xzqhCxtj.getXkzh().length() > 0) {
                    xzqhList = cb08XzqhMapper.getXzqhXkzh(fistXzq, xzqhCxtj.getXkzh(), xzqhCxtj.getNd());
                }


            } else {
                xzqhListsel = cb08XzqhMapper.selXzqhDm(fistXzq);
                xzqhList.addAll(xzqhListsel);
            }

            if (xzqhList != null && xzqhList.size() > 0 && !xzqhList.contains(xzqhdm)) {
                xzqhList.add(xzqhdm);


            }
            //查询其所对应的市级行政区代码
            if (xzqhList != null && xzqhList.size() > 0) {
                String sql = "(";
                for (String xzq : xzqhList) {
                    sql += "'" + xzq + "',";
                }
                sql = sql.substring(0, sql.length() - 1) + ")";
                List<String> xzqdms = cb08XzqhMapper.getXzqhfdm(sql);
                xzqhList.addAll(xzqdms);
                if (!xzqhList.contains(xzqhdm)) {
                    xzqhList.add(xzqhdm);
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return xzqhList;
    }

    /**
     * 读取mdb数据
     *
     * @param ks
     * @param file
     */
    public void getMdaKsData(Ks ks, MultipartFile file) {

        //文件名称
        String fileName = file.getOriginalFilename();
        if (!fileName.toUpperCase(Locale.ROOT).contains(".MDB")) {
            throw new CommonException("不是.mdb文件格式");
        }
        File file1 = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + fileName);
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), file1);

            String tableName = "";

            if (ks.getDjflbh() == 1000) {
                tableName = "勘查项目登记";
            }
            if (2000 <= ks.getDjflbh() && ks.getDjflbh() < 3000) {
                tableName = "采矿申请登记";
            }
            List<Map<String, Object>> records = MdbTool.readMdbFile(file1.getPath(), tableName);
            if (records.size() == 1) {
                matchingData(ks, records.get(0));

            } else {
                throw new CommonException(fileName + "该文件数据不正确");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            FileUtil.del(file1);
        }
    }

    /**
     * 同步mdb数据
     *
     * @param ks
     * @param stringObjectMap
     */
    private void matchingData(Ks ks, Map<String, Object> stringObjectMap) {
        if (ks.getDjflbh() == 1000) {
            Object djq = stringObjectMap.get("东经起");
            if (djq != null) {
                ks.setDjq((double) djq);
            }
            Object djz = stringObjectMap.get("东经止");
            if (djz != null) {
                ks.setDjz((double) djz);
            }
            Object bwq = stringObjectMap.get("北纬起");
            if (bwq != null) {
                ks.setBwq((double) bwq);
            }
            Object bwz = stringObjectMap.get("北纬止");
            if (bwz != null) {
                ks.setBwz((double) bwz);
            }
            Object xkzh = stringObjectMap.get("许可证号");
            if (xkzh != null) {
                ks.setXkzh((String) xkzh);
            }
            Object xzqdm = stringObjectMap.get("所在行政区");
            if (xzqdm != null) {
                ks.setXzqdm((int) xzqdm);
            }
            Object zkcm = stringObjectMap.get("勘查矿种");
            if (zkcm != null) {
                ks.setZkcm((int) zkcm);
            }
        } else if (2000 <= ks.getDjflbh() && ks.getDjflbh() < 3000) {
            Object xkzh = stringObjectMap.get("许可证号");
            if (xkzh != null) {
                ks.setXkzh((String) xkzh);
            }
            Object xzqdm = stringObjectMap.get("行政区代码");
            if (xzqdm != null) {
                ks.setXzqdm((int) xzqdm);
            }
            Object xm = stringObjectMap.get("所在行政区名称");
            if (xm != null) {
                ks.setXm((String) xm);
            }
            Object ksmc = stringObjectMap.get("矿山名称");
            if (ksmc != null) {
                ks.setKsmc((String) ksmc);
            }
            Object zkcm = stringObjectMap.get("开采主矿种");
            if (zkcm != null) {
                ks.setZkcm((int) zkcm);
            }
            Object shxydm = stringObjectMap.get("申请人信用代码");
            if (shxydm != null) {
                ks.setShxydm((String) shxydm);
            }
            Object kyqr = stringObjectMap.get("申请人");
            if (kyqr != null) {
                ks.setKyqr((String) kyqr);
            }
            Object yzbm = stringObjectMap.get("邮编");
            if (yzbm != null) {
                ks.setYzbm((String) yzbm);
            }
            Object djq = stringObjectMap.get("东经起");
            if (djq != null) {
                ks.setDjq((double) djq);
            }
            Object djz = stringObjectMap.get("东经止");
            if (djz != null) {
                ks.setDjz((double) djz);
            }
            Object bwq = stringObjectMap.get("北纬起");
            if (bwq != null) {
                ks.setBwq((double) bwq);
            }
            Object bwz = stringObjectMap.get("北纬止");
            if (bwz != null) {
                ks.setBwz((double) bwz);
            }
        }
        if (stringObjectMap.get("区域坐标") != null) {
            Zb zb = new Zb();
            zb.setKqbh(ks.getKqbh());
            zb.setDjflbh(ks.getDjflbh());
            zb.setNd(ks.getNd());
            zb.setKqzb((String) stringObjectMap.get("区域坐标"));
            iZbService.save(zb);
        }


    }
}
